package com.xiaoqi.android_system_project;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

/*
* 自定义监听系统应用的服务
* */
import androidx.annotation.Nullable;

import java.util.ArrayList;

public class ListenSystemService extends Service {

    private ActivityManager am;
    private static ArrayList list = new ArrayList<>();
    public ListenSystemService() {
        Log.i("System","service构造器");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
                 ArrayList memInfo = getMemInfo(getApplicationContext());
                System.out.println("发送消息成功");
                Message message = MainActivity.handler.obtainMessage();// 创建消息对象
                // 讲音乐总时长和播放进度封装到消息对象中
                Bundle bundle = new Bundle();
                bundle.putString("availMem", (String) memInfo.get(0));
                bundle.putString("totalMem", (String) memInfo.get(1));
                bundle.putString("lowMem", (String) memInfo.get(2));
                message.setData(bundle);
                // 将消息放松到主线程的消息队列
                MainActivity.handler.sendMessage(message);
                Log.i("Mediaplayer","发送消息成功   ");
        return super.onStartCommand(intent, flags, startId);
    }

    // 获得设备内存信息
    public static ArrayList getMemInfo(Context mContext) {
        float availMem;
        float totalMem;
        boolean lowMem;
        // 得到ActivityManager
        // 创建ActivityManager.MemoryInfo对象
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);

        // 取得剩余的内存空间
        availMem = mi.availMem / 1024 / 1024 / 1024f;
        totalMem = mi.totalMem / 1024 / 1024 / 1024f;
        lowMem = mi.lowMemory;

        System.out.println("设备总内存:" + String.format("%.2f", totalMem) + "/n");
        System.out.println("设备可用内存:" + String.format("%.2f", availMem) + "/n");
        System.out.println("是否低内存状态:" + mi.lowMemory);

        list.add(String.format("%.2f", totalMem)+"G");
        list.add(String.format("%.2f", availMem)+"G");
        list.add(mi.lowMemory+"");
        return list;
    }

}
